<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :scroll="{ y: '70vh' }"
      bordered
      :loading="loading"
      :rowClassName="setRowClassName"
      :pagination="false"
    >
      <span slot="deviceIdsTxt" slot-scope="deviceIdsTxt">{{ devName }}{{ getSeiresDevsn(deviceIdsTxt) }}</span>
      <span slot="efficiency" slot-scope="text">{{ (Number(text) * 100).toFixed(2) }}%</span>
      <span slot="currentActualOutput" slot-scope="text">{{ Number(text).toFixed(2) }}</span>
      <span slot="consumption" slot-scope="text">{{ Number(text).toFixed(2) }}</span>
      <span slot="consumptionPerTon" slot-scope="text">{{ Number(text).toFixed(2) }}</span>
    </a-table>
  </div>
</template>

<script>
export default {
  props: {
    scrollY: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: true
    },
    tableData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      devName: '',
      dataSource: [],
      columns: [
        {
          title: '日期',
          dataIndex: 'planTime',
          key: 'planTime'
        },
        {
          title: '车间',
          dataIndex: 'workshop_dictText',
          key: 'workshop'
        },
        {
          title: '品种',
          title: () => (
            <div>
              品种
              <a-icon type="caret-up" class="sort-icon" onClick={() => this.tableSort('productTypeTxt', 'ascend')} />
              <a-icon type="caret-down" class="sort-icon" onClick={() => this.tableSort('productTypeTxt', 'descend')} />
            </div>
          ),
          dataIndex: 'productTypeTxt',
          key: 'productTypeTxt'
        },
        {
          // title: '车台号',
          title: () => (
            <div>
              车台号
              <a-icon type="caret-up" class="sort-icon" onClick={() => this.tableSort('deviceIdsTxt', 'ascend')} />
              <a-icon type="caret-down" class="sort-icon" onClick={() => this.tableSort('deviceIdsTxt', 'descend')} />
            </div>
          ),
          dataIndex: 'deviceIdsTxt',
          key: 'deviceIdsTxt',
          scopedSlots: { customRender: 'deviceIdsTxt' }
        },
        {
          // title: '产量(米)',
          title: () => (
            <div>
              产量(米)
              <a-icon
                type="caret-up"
                class="sort-icon"
                // style={{ color: this.sortColumn === 'length' && this.sortOrder === 'ascend' ? '#1890ff' : '#bfbfbf' }}
                onClick={() => this.tableSort('length', 'ascend')}
              />
              <a-icon
                type="caret-down"
                class="sort-icon"
                // style={{ color: this.sortColumn === 'length' && this.sortOrder === 'descend' ? '#1890ff' : '#bfbfbf' }}
                onClick={() => this.tableSort('length', 'descend')}
              />
            </div>
          ),
          dataIndex: 'length',
          key: 'length'
        },
        {
          title: '当前实际产量(kg)',
          title: () => (
            <div>
              当前实际产量(kg)
              <a-icon
                type="caret-up"
                class="sort-icon"
                onClick={() => this.tableSort('currentActualOutput', 'ascend')}
              />
              <a-icon
                type="caret-down"
                class="sort-icon"
                onClick={() => this.tableSort('currentActualOutput', 'descend')}
              />
            </div>
          ),
          dataIndex: 'currentActualOutput',
          key: 'currentActualOutput',
          scopedSlots: { customRender: 'currentActualOutput' }
        },
        {
          // title: '耗电量(kw/h)',
          title: () => (
            <div>
              耗电量(kw/h)
              <a-icon type="caret-up" class="sort-icon" onClick={() => this.tableSort('consumption', 'ascend')} />
              <a-icon type="caret-down" class="sort-icon" onClick={() => this.tableSort('consumption', 'descend')} />
            </div>
          ),
          dataIndex: 'consumption',
          key: 'consumption',
          scopedSlots: { customRender: 'consumption' }
        },
        {
          // title: '吨纱电耗(kw/吨)',
          title: () => (
            <div>
              吨纱电耗(kw/吨)
              <a-icon type="caret-up" class="sort-icon" onClick={() => this.tableSort('consumptionPerTon', 'ascend')} />
              <a-icon
                type="caret-down"
                class="sort-icon"
                onClick={() => this.tableSort('consumptionPerTon', 'descend')}
              />
            </div>
          ),
          dataIndex: 'consumptionPerTon',
          key: 'consumptionPerTon',
          scopedSlots: { customRender: 'consumptionPerTon' }
        }
      ]
    }
  },
  watch: {
    //筛选tableData
    tableData: {
      immediate: true,
      handler(newVal, oldVal) {
        this.dataSource = newVal
      },
      deep: true
    }
  },

  methods: {
    // 获取连续车台
    getSeiresDevsn(arr) {
      arr = arr.split(',')
      var result = [],
        i = 0,
        str = ''
      if (arr.length > 0) {
        result[i] = [arr[0]]
        arr.reduce(function(prev, cur) {
          parseInt(cur) - parseInt(prev) === 1 ? result[i].push(cur) : (result[++i] = [cur])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str += `${item[0]}-${item[item.length - 1]}、`
          } else {
            str += `${item[0]}、`
          }
        })
        str = str.substring(0, str.length - 1)
      } else {
        str = ''
      }
      return str
    },
    // 根据name判断排序的列，根据order判断排序规则
    tableSort(name, order) {
      //删除拼接id的条目
      this.dataSource = this.dataSource.filter(item => !item.isStatistics)
      //根据规则排序
      const sortedData = [...this.dataSource].sort((a, b) => {
        switch (name) {
          case 'productTypeTxt':
            return order === 'ascend'
              ? a.productTypeTxt.localeCompare(b.productTypeTxt)
              : b.productTypeTxt.localeCompare(a.productTypeTxt)
          case 'length':
            return order === 'ascend' ? a.length - b.length : b.length - a.length
          case 'deviceIdsTxt':
            return order === 'ascend'
              ? parseInt(a.deviceIdsTxt) - parseInt(b.deviceIdsTxt)
              : parseInt(b.deviceIdsTxt) - parseInt(a.deviceIdsTxt)
          case 'currentActualOutput':
            return order === 'ascend'
              ? a.currentActualOutput - b.currentActualOutput
              : b.currentActualOutput - a.currentActualOutput
          case 'consumption':
            return order === 'ascend' ? a.consumption - b.consumption : b.consumption - a.consumption
          case 'consumptionPerTon':
            return order === 'ascend'
              ? a.consumptionPerTon - b.consumptionPerTon
              : b.consumptionPerTon - a.consumptionPerTon
          default:
            return 0
        }
      })
      //排序后调用processData方法将连续序号相同品种的集合对象插入数组，参数是排序后的数组（先排序后插入）
      this.processData(sortedData)
    },
    processData(sortedData) {
      // console.log('执行了processData', sortedData)
      let result = []
      let planTime = sortedData[0].planTime
      let workshop = sortedData[0].workshop
      let workshop_dictText = sortedData[0].workshop_dictText
      let lengthSum = 0
      let currentActualOutputSum = 0
      let consumptionSum = 0
      let consumptionPerTonSum = 0
      let start = null
      let end = null
      let currentType = null //品种

      for (let i = 0; i < sortedData.length; i++) {
        if (start === null) {
          start = sortedData[i].deviceIdsTxt
          currentType = sortedData[i].productTypeTxt
        }
        if (
          i < sortedData.length - 1 &&
          sortedData[i + 1].productTypeTxt === currentType &&
          parseInt(sortedData[i + 1].deviceIdsTxt) === parseInt(sortedData[i].deviceIdsTxt) + 1
        ) {
          lengthSum += sortedData[i].length
          currentActualOutputSum += sortedData[i].currentActualOutput
          consumptionSum += sortedData[i].consumption
          consumptionPerTonSum += sortedData[i].consumptionPerTon
          end = sortedData[i + 1].deviceIdsTxt
          result.push(sortedData[i])
        } else {
          lengthSum += sortedData[i].length
          currentActualOutputSum += sortedData[i].currentActualOutput
          consumptionSum += sortedData[i].consumption
          consumptionPerTonSum += sortedData[i].consumptionPerTon
          if (start !== end && end !== null) {
            result.push(sortedData[i])
            result.push({
              productTypeTxt: currentType,
              deviceIdsTxt: `${start}-${end}`,
              length: lengthSum,
              planTime: planTime,
              workshop: workshop,
              workshop_dictText: workshop_dictText,
              currentActualOutput: currentActualOutputSum,
              consumption: consumptionSum,
              consumptionPerTon: consumptionPerTonSum,
              isStatistics: true
            })
          } else {
            result.push(sortedData[i])
          }
          start = sortedData[i + 1] ? sortedData[i + 1].deviceIdsTxt : null
          end = null
          lengthSum = 0
          currentActualOutputSum = 0
          consumptionPerTonSum = 0
          consumptionSum = 0
          currentType = sortedData[i + 1] ? sortedData[i + 1].productTypeTxt : null
        }
      }

      let delIndexDefault = [] // 存放需要删除的索引值默认值
      let delIndex = [] // 存放需要删除的索引值（筛选后）
      let statisticsArr = [] // 存放需要操作的对象
      let newStatisticsArr = [] // 存放修改后的新对象

      result.forEach((item, index) => {
        if (item.isStatistics === true) {
          item.index = index // 多存入索引值用于区分需要被删除的对象的索引值
          delIndexDefault.push(index)
          statisticsArr.push(item)
        }
      })
      //二次处理数组，合并连续品种的不同连续机台
      let planTime2 = sortedData[0].planTime
      let workshop2 = sortedData[0].workshop
      let workshop_dictText2 = sortedData[0].workshop_dictText
      let lengthSum2 = 0
      let currentActualOutputSum2 = 0
      let consumptionSum2 = 0
      let consumptionPerTonSum2 = 0
      let deviceIdsTxt2 = ''
      let currentType2 = null //品种
      let index2 = -1

      // 拼接生成连续品种不同机台数组
      for (let i = 0; i < statisticsArr.length; i++) {
        // 如果不是最后一项（因为最后一项没有i+1）
        if (i < statisticsArr.length - 1) {
          // 如果和后一项相同就累加
          if (statisticsArr[i].productTypeTxt == statisticsArr[i + 1].productTypeTxt) {
            deviceIdsTxt2 = `${deviceIdsTxt2};${statisticsArr[i].deviceIdsTxt}`
            lengthSum2 = lengthSum2 += statisticsArr[i].length
            currentActualOutputSum2 = currentActualOutputSum2 += statisticsArr[i].currentActualOutput
            consumptionSum2 = consumptionSum2 += statisticsArr[i].consumption
            consumptionPerTonSum2 = consumptionPerTonSum2 += statisticsArr[i].consumptionPerTon
          }
          // 如果和后一项不相同就累加后压入数组，然后初始化暂存
          else {
            deviceIdsTxt2 = `${deviceIdsTxt2};${statisticsArr[i].deviceIdsTxt}`
            lengthSum2 = lengthSum2 += statisticsArr[i].length
            currentActualOutputSum2 = currentActualOutputSum2 += statisticsArr[i].currentActualOutput
            consumptionSum2 = consumptionSum2 += statisticsArr[i].consumption
            consumptionPerTonSum2 = consumptionPerTonSum2 += statisticsArr[i].consumptionPerTon
            currentType2 = statisticsArr[i].productTypeTxt
            index2 = statisticsArr[i].index
            newStatisticsArr.push({
              productTypeTxt: currentType2,
              deviceIdsTxt: deviceIdsTxt2,
              length: lengthSum2,
              planTime: planTime2,
              workshop: workshop2,
              workshop_dictText: workshop_dictText2,
              currentActualOutput: currentActualOutputSum2,
              consumption: consumptionSum2,
              consumptionPerTon: consumptionPerTonSum2,
              isStatistics: true,
              index: index2
            })
            lengthSum2 = 0
            currentActualOutputSum2 = 0
            consumptionSum2 = 0
            consumptionPerTonSum2 = 0
            deviceIdsTxt2 = ''
            currentType2 = null //品种
            index2 = -1
          }
        }
        // 如果是最后一项
        else {
          // 如果与前一项不相同就直接压入自己
          if (statisticsArr[i].productTypeTxt != statisticsArr[i - 1].productTypeTxt) {
            newStatisticsArr.push({
              productTypeTxt: statisticsArr[i].productTypeTxt,
              deviceIdsTxt: statisticsArr[i].deviceIdsTxt,
              length: statisticsArr[i].length,
              planTime: planTime2,
              workshop: workshop2,
              workshop_dictText: workshop_dictText2,
              currentActualOutput: statisticsArr[i].currentActualOutput,
              consumption: statisticsArr[i].consumption,
              consumptionPerTon: statisticsArr[i].consumptionPerTon,
              isStatistics: true,
              index: statisticsArr[i].index
            })
          }
          // 如果与前一项相同就累加后压入自己
          else if (statisticsArr[i].productTypeTxt == statisticsArr[i - 1].productTypeTxt) {
            deviceIdsTxt2 = `${deviceIdsTxt2};${statisticsArr[i].deviceIdsTxt}`
            lengthSum2 = lengthSum2 += statisticsArr[i].length
            currentActualOutputSum2 = currentActualOutputSum2 += statisticsArr[i].currentActualOutput
            consumptionSum2 = consumptionSum2 += statisticsArr[i].consumption
            consumptionPerTonSum2 = consumptionPerTonSum2 += statisticsArr[i].consumptionPerTon
            currentType2 = statisticsArr[i].productTypeTxt
            index2 = statisticsArr[i].index
            newStatisticsArr.push({
              productTypeTxt: currentType2,
              deviceIdsTxt: deviceIdsTxt2,
              length: lengthSum2,
              planTime: planTime2,
              workshop: workshop2,
              workshop_dictText: workshop_dictText2,
              currentActualOutput: currentActualOutputSum2,
              consumption: consumptionSum2,
              consumptionPerTon: consumptionPerTonSum2,
              isStatistics: true,
              index: index2
            })
          }
        }
      }
      // 去除因为拼接生成的第一个分号'；'
      newStatisticsArr.forEach(item => {
        if (item.deviceIdsTxt.includes(';')) {
          item.deviceIdsTxt = item.deviceIdsTxt.replace(';', '')
        }
        // 覆盖掉result里面的
        result[item.index] = item
      })
      // 筛选出要被删除的索引值,创建用于删除的索引数组
      delIndexDefault.forEach(item => {
        if (!newStatisticsArr.some(obj => obj.index == item)) {
          delIndex.push(item)
        }
      })
      result = result.filter((_, index) => !delIndex.includes(index))

      this.dataSource = result

      console.log('this.dataSourceresres', this.dataSource)
    },
    setRowClassName(record) {
      return record.isStatistics == true ? 'red-row' : ''
    }
  }
}
</script>

<style lang="less">
.red-row {
  color: red;
}
</style>
